<template>
  <div class="search-collapse">
    <div
      class="form-search"
      :style="{ height: isFold ? props.mixHeight + 'px' : '' }"
    >
      <div ref="collapseContainerRef">
        <slot></slot>
      </div>
    </div>
    <div class="control-search">
      <slot name="control"></slot>

      <template v-if="isCollapse">
        <template v-if="btnStyle === 'default'">
          <el-button
            type="primary"
            link
            v-if="isFold"
            @click="handleToggleCollapse"
          >
            展开
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </el-button>
          <el-button type="primary" link v-else @click="handleToggleCollapse">
            收起
            <el-icon class="el-icon--right">
              <ArrowUp />
            </el-icon>
          </el-button>
        </template>
        <template v-if="btnStyle === 'simple'">
          <el-button
            v-if="isFold"
            type="primary"
            link
            :icon="ArrowDown"
            @click="handleToggleCollapse"
          >
          </el-button>
          <el-button
            v-else
            type="primary"
            link
            :icon="ArrowUp"
            @click="handleToggleCollapse"
          >
          </el-button>
        </template>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';

const props = defineProps({
  // 默认自动展开
  autoSpread: {
    type: Boolean,
    default: false
  },

  // 最小折叠高度
  mixHeight: {
    type: Number,
    default: 40
  },

  // 按钮风格，default-普通风格，simple-极简风格
  btnStyle: {
    type: String,
    default: 'default',
    validator: (value: string) => ['default', 'simple'].includes(value)
  }
});

// 是否折叠
const isFold = ref<boolean>(true);
// 是否可折叠
const isCollapse = ref<boolean>(false);
// div - ref
const collapseContainerRef = ref<HTMLDivElement>();

// watch
watch(
  () => props.autoSpread,
  (val) => {
    isFold.value = !val;
  },
  {
    immediate: true
  }
);

// [折叠|展开]
const handleToggleCollapse = () => {
  isFold.value = !isFold.value;
};

// 初始化高度
const initScorllHeight = () => {
  if (!collapseContainerRef.value) return;
  const height = collapseContainerRef.value?.scrollHeight;
  // 如果大于两倍高度，则显示折叠按钮，其中最小高度与".fold"保持一致
  isCollapse.value = height >= props.mixHeight * 2;
};

onMounted(() => {
  initScorllHeight();
});
</script>

<style lang="scss" scope>
.search-collapse {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;

  .form-search {
    flex: 1;
    overflow: hidden;

    &.fold {
      height: 40px;
    }

    .el-form-item {
      margin-bottom: 8px;
    }

    .el-input__inner {
      padding-right: 0;
    }
  }

  .control-search {
    padding: 0 0 8px;
    display: flex;
    align-items: center;
  }
}
</style>
